<template>
	<a-row :class="['p-2', `${prefixCls}--box`]" type="flex" :gutter="10">
		<a-col :xl="6" :lg="24" :md="24" style="margin-bottom: 10px">
			<DepartLeftTree ref="leftTree" @select="onTreeSelect" @rootTreeData="onRootTreeData" />
		</a-col>
		<a-col :xl="18" :lg="24" :md="24" style="margin-bottom: 10px">
			<!--引用表格-->
			<BasicTable @register="registerTable" :rowSelection="rowSelection" :searchInfo="searchInfo">
				<!--插槽:table标题-->
				<template #tableTitle>
					<a-button type="primary" @click="handleAdd" preIcon="ant-design:plus-outlined"> 新增</a-button>
					<a-button type="primary" @click="handleAddTravel" preIcon="ant-design:import-outlined">
						从其它旅行社新增</a-button>
					<a-button type="primary" preIcon="ant-design:export-outlined" @click="handleExport">
						导出到其它旅行社</a-button>
					<!-- 	<j-upload-button type="primary" preIcon="ant-design:import-outlined"
					@click="onImportXls">导入</j-upload-button>
				<a-dropdown v-if="selectedRowKeys.length > 0">
					<template #overlay>
						<a-menu>
							<a-menu-item key="1" @click="batchHandleDelete">
								<Icon icon="ant-design:delete-outlined"></Icon>
								删除
							</a-menu-item>
						</a-menu>
					</template>
					<a-button>批量操作
						<Icon icon="mdi:chevron-down"></Icon>
					</a-button>
				</a-dropdown> -->
				</template>
				<!--操作栏-->
				<template #action="{ record }">
					<TableAction :actions="getTableAction(record)" :dropDownActions="getDropDownAction(record)" />
				</template>
				<!--字段回显插槽-->
				<template v-slot:bodyCell="{ column, record, index, text }">
				</template>
			</BasicTable>
		</a-col>
		<!-- 表单区域 -->
		<!-- 	<BsTravelgroupTourorderrecordModal @register="registerModal" @success="handleSuccess">
		</BsTravelgroupTourorderrecordModal> -->
		<updateUpCarAddressIdModule @register="registerUpCarAddressModal" @successConfirm="handleSuccess">
		</updateUpCarAddressIdModule>
		<updateJouneryModule @register="registerUpdateJouneryModal" @successConfirm="handleSuccess">
		</updateJouneryModule>
		<giveTicketModule @register="registerTicketModal" @successConfirm="handleSuccess">
		</giveTicketModule>
		<refundPriceModule @register="registerRefundModal" @successConfirm="handleSuccess">
		</refundPriceModule>
		<BsTravelgroupTourorderrecordTravelBigModal @register="registerTravelModal" @success="handleSuccess">
		</BsTravelgroupTourorderrecordTravelBigModal>
		<BsTravelgroupTourorderrecordExportTravelBigModal @register="registerTravelExportModal"
			@successExcelData="successExcelData">
		</BsTravelgroupTourorderrecordExportTravelBigModal>

		<!-- 表单区域 -->
		<DetailDrawer @register="registerDrawer" @success="handleSuccess">
		</DetailDrawer>
		<uploadStatsModal @register="registerUploadStatsModal" @successConfirm="uploadStatsModalFun" />
	</a-row>
</template>

<script lang="ts" name="journey-bsTravelgroupTourorderrecord" setup>
	import { ref, computed, unref, inject, watch } from 'vue';
	import { BasicTable, useTable, TableAction } from '/@/components/Table';
	import { useModal } from '/@/components/Modal';
	import { isEmpty } from "/@/utils/is";
	import { useListPage } from '/@/hooks/system/useListPage'
	//import BsTravelgroupTourorderrecordModal from '../components/BsTravelgroupTourorderrecordBigModal.vue'
	import BsTravelgroupTourorderrecordTravelBigModal from '../components/BsTravelgroupTourorderrecordTravelBigModal.vue'
	import BsTravelgroupTourorderrecordExportTravelBigModal from '../components/BsTravelgroupTourorderrecordExportTravelBigModal.vue'
	import { columns, searchFormSchema } from '../BsTravelgroupTourorderrecordBig.data';
	import { getOrderDetailInfoById } from './BsTravelgroupTourorderrecord.api';
	import { listByMainId, deleteOne, batchDelete, getImportUrl, getExportUrl, refundOrCancelJounery } from '../BsTravelgroupTourorderrecord.api';
	import { downloadFile } from '/@/utils/common/renderUtils';
	import updateUpCarAddressIdModule from '../module/updateUpCarAddressIdModule.vue';
	import updateJouneryModule from '../../../../module/jounery/updateJouneryModule.vue';
	import refundPriceModule from '../../../../module/jounery/refundPriceModule.vue';
	import giveTicketModule from '../../../../module/jounery/giveTicketModule.vue';
	import { useUserStore } from '/@/store/modules/user';
	import { useMessage } from '/@/hooks/web/useMessage';
	import DepartLeftTree from './order/components/DepartLeftTree.vue';
	import { useDrawer } from '/@/components/Drawer';
	import DetailDrawer from './drawer/index.vue'
	import { saveAs } from 'file-saver';
	import * as XLSX from 'xlsx';
	const mainId = ref('');
	const $message = useMessage()
	const searchInfo = {};
	const checkedKeys = ref<Array<string | number>>([]);
	const userStore = useUserStore();


	const [registerUploadStatsModal, { openModal: openUpdateModal }] = useModal();
	const [registerDrawer, { openDrawer, closeDrawer }] = useDrawer();
	const lstData = ref([] as Array)
	const travelgroupid = ref("")
	//注册model
	const [registerModal, { openModal }] = useModal();
	const [registerUpCarAddressModal, { openModal: upCarAddressModal }] = useModal();
	const [registerUpdateJouneryModal, { openModal: opUpdateJouneryModal }] = useModal();
	const [registerTicketModal, { openModal: opTicketModal }] = useModal();
	const [registerRefundModal, { openModal: opRefundModal }] = useModal();
	const [registerTravelModal, { openModal: openTravelModal }] = useModal();
	const [registerTravelExportModal, { openModal: openTravelExportModal }] = useModal();
	//注册table数据
	const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
		tableProps: {
			title: '报名记录',
			api: listByMainId,
			columns,
			canResize: false,
			formConfig: {
				//labelWidth: 120,
				schemas: searchFormSchema,
				autoSubmitOnEnter: true,
				showAdvancedButton: true,
				fieldMapToNumber: [
				],
				fieldMapToTime: [
				],
			},
			beforeFetch(params) {
				params.travelgroupid = travelgroupid.value
				params.category = 'Group'
				return params
			},
			actionColumn: {
				width: 120,
				fixed: 'right'
			},
		},
		exportConfig: {
			name: "报名记录",
			url: getExportUrl,
		},
		importConfig: {
			url: getImportUrl,
			success: handleSuccess
		},
	})

	const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext
	watch(mainId, () => {
		searchInfo['travelgroupid'] = unref(mainId);
		reload();
	})

	function handleAddTravel() {
		if (isEmpty(unref(mainId))) {
			$message.createMessage.warning('请选择一个主表信息')
			return;
		}
		openTravelModal(true, {
			mainId: unref(mainId),
			isUpdate: false,
			showFooter: true,
		})
	}

	//导出 Excel
	function successExcelData(datas) {
		if (datas.length == 0) {
			return $message.createMessage.warning('无报名人员不导出')
		}
		// 表格数据
		console.log(datas, '----->140')
		// 转化为工作簿对象
		const workbook = XLSX.utils.book_new();
		// 表头
		const header = [
			'姓名',
			'电话',
			'身份证',
			'行程标题',
		];
		// 表头对应的键名
		const keys = [
			'userName',
			'userPhone',
			'idCard',
			'titel',
		];
		// 表格数据处理
		const arr = [];
		datas.forEach(item => {
			const obj = {};
			keys.forEach((key, i) => {
				obj[header[i]] = item[key];
			});
			arr.push(obj);
		});
		// 创建工作表
		const worksheet = XLSX.utils.json_to_sheet(arr, { header });
		// 将工作表添加到工作簿
		XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
		// 导出 Excel
		XLSX.writeFile(workbook, '游客数据.xlsx');
	}

	function handleExport() {
		if (isEmpty(unref(mainId))) {
			$message.createMessage.warning('请选择一个主表信息')
			return;
		}
		openTravelExportModal(true, {
			mainId: unref(mainId),
			isUpdate: false,
			showFooter: true,
		})
	}
	async function onTreeSelect(m) {
		if (m.orgType == 1) return
		mainId.value = m.id

		//setProps({travelgroupid:m.id})
		travelgroupid.value = m.id
		reload()
		/* let ls=await list({travelgroupid:m.id});
		lstData.value=ls.records
		setTableData(lstData.value) */

	}

	function uploadStatsModalFun() {
		reload()
	}
	/**
	 * 新增事件
	 */
	function handleAdd() {
		if (isEmpty(unref(mainId))) {
			$message.createMessage.warning('请选择一个主表信息')
			return;
		}
		openModal(true, {
			mainId: unref(mainId),
			isUpdate: false,
			showFooter: true,
		});
	}
	/**
	 * 编辑事件
	 */
	/* 	function handleEdit(record : Recordable) {
			record.mainId = unref(mainId)
			record.isUpdate = true
			if (record.signcontract) {
				record.signcontract = "true"
			} else {
				record.signcontract = "false"
			}
			openModal(true, {
				record,
				isUpdate: true,
				showFooter: true,
			});
		} */

	async function handleEdit(record : Recordable) {

		console.log(record, '---->135')
		//先请求接口，通过订单id查询返回
		let res = await getOrderDetailInfoById({ id: record.id });
		res.upCarPoint = record.upCarPoint

		openDrawer(true, {
			res,
			showFooter: true
		});

		/* openModal(true, {
			record,
			isUpdate: true,
			showFooter: true,
		}); */
	}

	/**
	 * 详情
	*/
	function handleDetail(record : Recordable) {
		record.isUpdate = true
		if (record.signcontract) {
			record.signcontract = "true"
		} else {
			record.signcontract = "false"
		}
		openModal(true, {
			record,
			isUpdate: true,
			showFooter: false,
		});
	}
	/**
	 * 删除事件
	 */
	async function handleDelete(record) {
		await deleteOne({ id: record.id }, handleSuccess);
	}
	/**
	 * 批量删除事件
	 */
	async function batchHandleDelete() {
		await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
	}
	/**
	 * 成功回调
	 */
	function handleSuccess() {
		(selectedRowKeys.value = []) && reload();
	}
	/**
	   * 操作栏
	   */
	function getTableAction(record) {
		return [
			{
				label: '编辑',
				onClick: handleEdit.bind(null, record),
			}
		]
	}
	function handleChangeUpCarAddress(record) {
		console.log(record)

		upCarAddressModal(true, {
			mainId: record.travelgroupid,
			orderId: record.id,
			toAddressId: record.startpoint,
			isUpdate: false,
			showFooter: true
		})

	}

	async function handleRefund(record, tag) {
		if (tag == 3 || tag == 5) {
			opRefundModal(true, {
				orderId: record.id,
				tag: tag,
				isUpdate: false,
				showFooter: true,
			})

		} else {
			//直接请求后端
			//await 
			await refundOrCancelJounery({ id: record.id, refundType: tag }, reload());


		}
	}
	function handleChangeJounery(record, tag) {
		opUpdateJouneryModal(true, {
			orderId: record.id,
			isUpdate: false,
			showFooter: true,
		})
	}

	function handleComplimentaryCouponByOrderId(record, tag) {

		opTicketModal(true, {
			orderId: record.id,
			isUpdate: false,
			showFooter: true,
		})
	}



	/**
	   * 下拉操作栏
	   */
	function getDropDownAction(record) {
		return [
			{
				label: '详情',
				onClick: handleDetail.bind(null, record),
			}, {
				label: '更换行程',
				onClick: handleChangeJounery.bind(null, record),
				ifShow: (_action) => {
					return record.stats != 'Out' && record.stats != 'Payback'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			}, {
				label: '赠送优惠券',
				onClick: handleComplimentaryCouponByOrderId.bind(null, record),
			}, {
				label: '更换上车地点',
				onClick: handleChangeUpCarAddress.bind(null, record),
				ifShow: (_action) => {
					return record.stats != 'Out' && record.stats != 'Payback'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			}, {
				label: '取消并退全款',
				popConfirm: {
					title: '是否确认取消该用户报名并全额退款？',
					confirm: handleRefund.bind(null, record, 1),
					placement: 'topLeft',
				},
				ifShow: (_action) => {
					return record.stats == 'Join' || record.stats == 'Payed'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			},
			{
				label: '取消并按规则退款',
				popConfirm: {
					title: '是否确认取消该用户报名并按退款规则退款',
					confirm: handleRefund.bind(null, record, 2),
					placement: 'topLeft',
				},
				ifShow: (_action) => {
					return record.stats == 'Join' || record.stats == 'Payed'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			},
			{
				label: '不退款并取消行程报名',
				popConfirm: {
					title: '是否确认自定义金额退款并取消行程报名',
					confirm: handleRefund.bind(null, record, 4),
					placement: 'topLeft',
				},
				ifShow: (_action) => {
					return record.stats != 'Out' && record.stats != 'Payback'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			}, {
				label: '自定义金额退款不取消行程报名',
				onClick: handleRefund.bind(null, record, 3),
				ifShow: (_action) => {
					return record.stats == 'Join' || record.stats == 'Payed'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			}, {
				label: '自定义金额退款取消行程报名',
				onClick: handleRefund.bind(null, record, 5),
				ifShow: (_action) => {
					return record.stats == 'Join' || record.stats == 'Payed'; // 根据业务控制是否显示: 非enable状态的不显示启用按钮
				}
			},


		]
	}
</script>

<style scoped>

</style>